const keyPrefix = 'tjj-nb-666'

function loadFromStorage(key, defaultValue) {
    key = `${keyPrefix}-${key}`
    const getDefault = () => defaultValue instanceof Function ? defaultValue() : defaultValue
    let value = localStorage.getItem(key)
    if (!value) {
        value = getDefault()
    } else {
        try {
            value = JSON.parse(value)
        } catch {
            value = getDefault()
        }
    }
    window.addEventListener("beforeunload", () => {
        localStorage.setItem(key, JSON.stringify(value))
    })
    return value
}

export default loadFromStorage

